package com.wwdx.wechat.handler;

import com.google.common.collect.Lists;
import com.wwdx.model.WwdxOpenAuthModel;
import com.wwdx.model.WwdxWeixinUserModel;
import com.wwdx.utils.ConstantHolder;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author liguoliang
 */
public abstract class AbstractSubscribeHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        String openId = wxMessage.getFromUser();
        logger.info("新关注用户 OPENID: {}" , openId);
        //获取微信用户基本信息
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openId);
        WwdxWeixinUserModel model = wwdxWeixinUserService.getByOpenId(openId);
        String appId = wxMpService.getWxMpConfigStorage().getAppId(),authUrl;
        if (model == null){
            model = new WwdxWeixinUserModel();
            BeanUtils.copyProperties(wxMpUser,model);
            model.setAppid(appId);model.setGmtCreated(new Date());
            model.setGmtModified(new Date());
            wwdxWeixinUserService.save(model);
        }else {
            model.setGmtModified(new Date());
            wwdxWeixinUserService.update(model);
        }
        //蜜读学堂服务号
        if (merchantWxService.getWxMpConfigStorage().getAppId().equalsIgnoreCase(appId)){
            authUrl = wechatUrl+"auth.html?url="+wechatUrl+"index.html?merchantId="+openId;
            setOperations.add(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET, openId);
        }else {
            //分销商授权服务号
            WwdxOpenAuthModel wwdxOpenAuthModel = wwdxOpenAuthService.getByAppId(appId);
            if (wwdxOpenAuthModel == null){
                return null;
            }
            String merchantId = wwdxOpenAuthModel.getOpenId();
            authUrl = wxMpService.oauth2buildAuthorizationUrl(wechatUrl + "index.html?merchantId=" + merchantId, WxConsts.OAuth2Scope.SNSAPI_BASE, null);
        }
        //服务号订阅
        String key = String.format(ConstantHolder.MERCHANT_SUBSCRIBE_USER_SET, appId);
        setOperations.add(key,openId);
        setOperations.add(ConstantHolder.MERCHANT_SUBSCRIBE_SET,appId);
        //发送客服消息
        this.sendKefuMessage(openId,authUrl,wxMpService);
        return null;
    }

    private void sendKefuMessage(String openId,String authUrl,WxMpService service) throws WxErrorException{
        WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
        WxMpUser wxMpUser = service.getUserService().userInfo(openId);
        String picUrl = "http://mmbiz.qpic.cn/mmbiz_png/G8V8d8SnNEPo2icxhdPzAAB1992zYkv26HvpPYtKZ0RXFMo0oS0MtgibcVGlz9a6QWaEtMtntssicIBeSu1U6N9VA/0?wx_fmt=png";
        article.setPicUrl(picUrl);article.setUrl(authUrl);
        article.setDescription("@"+wxMpUser.getNickname()+"！欢迎来到蜜读听书，以帮助100多万听书用户奉献知识精华，点击免费领书。");
        List<WxMpKefuMessage.WxArticle> articles = Lists.newArrayList(article);
        service.getKefuService().sendKefuMessage(WxMpKefuMessage.NEWS().toUser(openId).articles(articles).build());
    }
}